package edu.ccut.saturn.basecomponent.databasecomponent;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import edu.ccut.saturn.basecomponent.database.facade.QueryBySQL;
import edu.ccut.saturn.basecomponent.database.util.SaturnMap;
import edu.ccut.saturn.component.IDataInfo;
import edu.ccut.saturn.component.IParameter;
import edu.ccut.saturn.component.IParameterContext;
import edu.ccut.saturn.component.SaturnData;
import edu.ccut.saturn.component.SaturnDataManager;

public class QueryBySaturnSQLComponent extends AbstractExecuteBySaturnSQL {
	@SuppressWarnings("unchecked")
	@Override
	public void execute(IParameterContext parameterContext) throws Exception {
		String fullKey = (String) parameterContext.getParameterValue(0);
		String sqlkey = (String)parameterContext.getParameterValue(1);
		List<String> expList = getParameterStr(parameterContext);
		IDataInfo dataInfo = SaturnDataManager.getInstance().getSaturnDataInfo(fullKey);
		String dbType = dataInfo.getDBType().toLowerCase();
		String sql = null;
		if(expList.size()>0){
			//有参数，则替换逻辑上下文中的参数
			Map<String,Object> customMap  = getCustomMap(expList,parameterContext);
			sql = dataInfo.getSqlById(sqlkey, customMap);
		}else{
			//无参数，则将逻辑上下文中的参数全部放到SaturnMap中
			SaturnMap customMap  = new SaturnMap(parameterContext);
			sql = dataInfo.getSqlById(sqlkey, customMap);
		}
		List<SaturnData> list = QueryBySQL.execute(fullKey, sql, dbType, parameterContext.getConnection());
		IParameter parameter= parameterContext.getParameter(2);
		if(ArrayList.class.getName().equals(parameter.getClassType().getName())){
			parameterContext.setParameter(2, list);
		}else{
			if(list==null)
			    parameterContext.setParameter(2, null);
			else
				parameterContext.setParameter(2, list.get(0));
		}
	}
}